package com.example.clipboardchecker;

import java.util.ArrayList;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.ClipboardManager;
import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.IBinder;
import android.os.Parcelable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class ClipListenService extends Service implements OnPrimaryClipChangedListener{

	private ClipboardManager cm;
	private static boolean service_running = false;


	@Override
	public int onStartCommand(Intent intent,int flags, int startid){
		
		cm = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		cm.addPrimaryClipChangedListener(this);
		
		
		
		service_running = true;
		
		Log.i(ClipboardCheckerActivity.INFO_TAG, "ClipService started!");
		return Service.START_STICKY;		
	}
	
	@Override
	public void onDestroy(){
		service_running = false;
		
		cm.removePrimaryClipChangedListener(this);
		Log.i(ClipboardCheckerActivity.INFO_TAG, "ClipService stopped");
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	@Override
	public void onPrimaryClipChanged() {
		Log.i(ClipboardCheckerActivity.INFO_TAG,"Clip changed!");
		//Toast.makeText(this, "Clip changed!", Toast.LENGTH_LONG).show();
		
		Intent resultInt = new Intent(this, ClipboardCheckerActivity.class);
		
		resultInt.setAction("notif");
		
		PendingIntent resultPendInt = PendingIntent.getActivity(getApplicationContext(), 0, resultInt, PendingIntent.FLAG_UPDATE_CURRENT);
		
		NotificationCompat.Builder builder =
				new NotificationCompat.Builder(this)
				.setSmallIcon(R.drawable.ic_launcher)
				.setContentTitle("Copydroid")
				.setContentText("Ein Text wurde in die Zwischenablage kopiert.")
				.setContentIntent(resultPendInt)
				.setAutoCancel(true);		
		
		((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(ClipboardCheckerActivity.ID, builder.build());
	}

	public static boolean isRunning() {
		return service_running;
	}
}
